/**
 * 认证弹窗管理模块
 * 提供注册和登录弹窗功能，支持 IndexedDB 存储用户信息
 */
(function () {
    // DOM 元素缓存
    let registerModal, loginModal, registerModalContent, loginModalContent, notification;
    let registerForm, loginForm;
    let userNameLink = null; // 用户名称显示元素

    // 回调函数
    let callbacks = {
        onRegisterSuccess: null,
        onLoginSuccess: null,
        onAutoLogin: null // 新增：自动登录回调
    };

    // IndexedDB 初始化
    let db;
    const DB_NAME = 'userDB';
    const STORE_NAME = 'users';

    // 打开数据库
    function openDatabase() {
        return new Promise((resolve, reject) => {
            const request = indexedDB.open(DB_NAME, 1);

            request.onupgradeneeded = (event) => {
                db = event.target.result;
                const objectStore = db.createObjectStore(STORE_NAME, { keyPath: 'email' });
                objectStore.createIndex('username', 'username', { unique: true });
                objectStore.createIndex('password', 'password', { unique: false });
            };

            request.onsuccess = (event) => {
                db = event.target.result;
                resolve(db);
            };

            request.onerror = (event) => {
                reject(`数据库错误: ${event.target.errorCode}`);
            };
        });
    }

    // 添加用户到数据库
    function addUser(user) {
        return new Promise((resolve, reject) => {
            const transaction = db.transaction([STORE_NAME], 'readwrite');
            const objectStore = transaction.objectStore(STORE_NAME);
            const request = objectStore.add(user);

            request.onsuccess = () => {
                resolve();
            };

            request.onerror = (event) => {
                if (event.target.error.name === 'ConstraintError') {
                    reject('用户名或邮箱已被注册');
                } else {
                    reject(`注册失败: ${event.target.error}`);
                }
            };
        });
    }

    // 通过邮箱查找用户
    function getUserByEmail(email) {
        return new Promise((resolve, reject) => {
            const transaction = db.transaction([STORE_NAME], 'readonly');
            const objectStore = transaction.objectStore(STORE_NAME);
            const request = objectStore.get(email);

            request.onsuccess = () => {
                resolve(request.result);
            };

            request.onerror = () => {
                reject(`查找用户失败`);
            };
        });
    }

    // 通过用户名查找用户
    function getUserByUsername(username) {
        return new Promise((resolve, reject) => {
            const transaction = db.transaction([STORE_NAME], 'readonly');
            const objectStore = transaction.objectStore(STORE_NAME);
            const index = objectStore.index('username');
            const request = index.get(username);

            request.onsuccess = () => {
                resolve(request.result);
            };

            request.onerror = () => {
                reject(`查找用户失败`);
            };
        });
    }

    // 创建弹窗元素
    function createModalElements() {
        // 创建文档片段，减少DOM操作
        const fragment = document.createDocumentFragment();

        // 创建注册模态框
        registerModal = document.createElement('div');
        registerModal.id = 'registerModal';
        registerModal.className = 'fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden';
        registerModal.innerHTML = `
            <div class="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 transform transition-all scale-95 opacity-0" id="registerModalContent">
                <div class="p-6">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-xl font-bold text-dark">创建账户</h3>
                        <button id="closeRegisterModal" class="text-gray-500 hover:text-gray-700 transition">
                            <i class="fa fa-times text-xl"></i>
                        </button>
                    </div>
                    
                    <form id="registerForm" class="space-y-4">
                        <div>
                            <label for="regUsername" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                            <div class="relative">
                                <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                    <i class="fa fa-user"></i>
                                </span>
                                <input type="text" id="regUsername" name="regUsername" 
                                    class="pl-10 w-full rounded-lg border border-gray-300 py-2.5 px-4 focus:outline-none form-input-focus"
                                    placeholder="请输入用户名" required>
                            </div>
                        </div>
                        
                        <div>
                            <label for="regEmail" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                            <div class="relative">
                                <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                    <i class="fa fa-envelope"></i>
                                </span>
                                <input type="email" id="regEmail" name="regEmail" 
                                    class="pl-10 w-full rounded-lg border border-gray-300 py-2.5 px-4 focus:outline-none form-input-focus"
                                    placeholder="请输入邮箱" required>
                            </div>
                        </div>
                        
                        <div>
                            <label for="regPassword" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                            <div class="relative">
                                <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                    <i class="fa fa-lock"></i>
                                </span>
                                <input type="password" id="regPassword" name="regPassword" 
                                    class="pl-10 w-full rounded-lg border border-gray-300 py-2.5 px-4 focus:outline-none form-input-focus"
                                    placeholder="请输入密码" required>
                            </div>
                        </div>
                        
                        <div>
                            <button type="submit" 
                                class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-2.5 px-4 rounded-lg btn-hover">
                                注册账户
                            </button>
                        </div>
                    </form>
                    
                    <div class="mt-4 text-center text-sm text-gray-600">
                        已有账户? <button id="switchToLogin" class="text-primary hover:underline">立即登录</button>
                    </div>
                </div>
            </div>
        `;
        fragment.appendChild(registerModal);

        // 创建登录模态框
        loginModal = document.createElement('div');
        loginModal.id = 'loginModal';
        loginModal.className = 'fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden';
        loginModal.innerHTML = `
            <div class="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 transform transition-all scale-95 opacity-0" id="loginModalContent">
                <div class="p-6">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-xl font-bold text-dark">登录账户</h3>
                        <button id="closeLoginModal" class="text-gray-500 hover:text-gray-700 transition">
                            <i class="fa fa-times text-xl"></i>
                        </button>
                    </div>
                    
                    <form id="loginForm" class="space-y-4">
                        <div>
                            <label for="loginIdentifier" class="block text-sm font-medium text-gray-700 mb-1">用户名或邮箱</label>
                            <div class="relative">
                                <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                    <i class="fa fa-user"></i>
                                </span>
                                <input type="text" id="loginIdentifier" name="loginIdentifier" 
                                    class="pl-10 w-full rounded-lg border border-gray-300 py-2.5 px-4 focus:outline-none form-input-focus"
                                    placeholder="请输入用户名或邮箱" required>
                            </div>
                        </div>
                        
                        <div>
                            <label for="loginPassword" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                            <div class="relative">
                                <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                    <i class="fa fa-lock"></i>
                                </span>
                                <input type="password" id="loginPassword" name="loginPassword" 
                                    class="pl-10 w-full rounded-lg border border-gray-300 py-2.5 px-4 focus:outline-none form-input-focus"
                                    placeholder="请输入密码" required>
                            </div>
                        </div>
                        
                        <div class="flex items-center justify-between">
                            <div class="flex items-center">
                                <input id="rememberMe" type="checkbox" class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded">
                                <label for="rememberMe" class="ml-2 block text-sm text-gray-700">记住我</label>
                            </div>
                            <div class="text-sm">
                                <a href="../admin_entrance_page/index.html" class="text-primary hover:underline">若忘记密码,请联系管理员</a>
                            </div>
                        </div>
                        
                        <div>
                            <button type="submit" 
                                class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-2.5 px-4 rounded-lg btn-hover">
                                登录
                            </button>
                        </div>
                    </form>
                    
                    <div class="mt-4 text-center text-sm text-gray-600">
                        还没有账户? <button id="switchToRegister" class="text-primary hover:underline">立即注册</button>
                    </div>
                </div>
            </div>
        `;
        fragment.appendChild(loginModal);

        // 创建通知元素
        notification = document.createElement('div');
        notification.id = 'notification';
        notification.className = 'fixed bottom-4 right-4 bg-white rounded-lg shadow-lg p-4 transform translate-y-10 opacity-0 transition-all duration-300 z-50 max-w-xs';
        notification.innerHTML = `
            <div class="flex items-start">
                <div id="notificationIcon" class="flex-shrink-0 mt-0.5">
                    <i class="fa fa-info-circle text-blue-500 text-xl"></i>
                </div>
                <div class="ml-3">
                    <h3 id="notificationTitle" class="text-sm font-medium text-gray-800">通知标题</h3>
                    <div id="notificationMessage" class="mt-1 text-sm text-gray-600">通知内容将显示在这里...</div>
                </div>
                <button id="closeNotification" class="ml-auto flex-shrink-0 text-gray-400 hover:text-gray-600">
                    <i class="fa fa-times"></i>
                </button>
            </div>
        `;
        fragment.appendChild(notification);

        // 将所有元素添加到文档中
        document.body.appendChild(fragment);

        // 获取内部元素引用
        registerModalContent = document.getElementById('registerModalContent');
        loginModalContent = document.getElementById('loginModalContent');
        registerForm = document.getElementById('registerForm');
        loginForm = document.getElementById('loginForm');
    }

    // 模态框动画函数
    function animateModal(modal, content, show = true) {
        if (show) {
            modal.classList.remove('hidden');
            setTimeout(() => {
                content.classList.remove('scale-95', 'opacity-0');
                content.classList.add('scale-100', 'opacity-100');
            }, 10);
        } else {
            content.classList.remove('scale-100', 'opacity-100');
            content.classList.add('scale-95', 'opacity-0');
            setTimeout(() => {
                modal.classList.add('hidden');
            }, 300);
        }
    }

    // 显示通知
    function showNotification(title, message, type = 'info') {
        const notificationEl = document.getElementById('notification');
        const notificationTitle = document.getElementById('notificationTitle');
        const notificationMessage = document.getElementById('notificationMessage');
        const notificationIcon = document.getElementById('notificationIcon').querySelector('i');

        // 设置通知内容
        notificationTitle.textContent = title;
        notificationMessage.textContent = message;

        // 设置通知类型图标和颜色
        notificationIcon.className = 'fa ';
        if (type === 'success') {
            notificationIcon.className += 'fa-check-circle text-green-500 text-xl';
        } else if (type === 'error') {
            notificationIcon.className += 'fa-exclamation-circle text-red-500 text-xl';
        } else if (type === 'warning') {
            notificationIcon.className += 'fa-exclamation-triangle text-yellow-500 text-xl';
        } else {
            notificationIcon.className += 'fa-info-circle text-blue-500 text-xl';
        }

        // 显示通知
        notificationEl.classList.remove('translate-y-10', 'opacity-0');
        notificationEl.classList.add('translate-y-0', 'opacity-100');

        // 3秒后自动关闭
        setTimeout(() => {
            hideNotification();
        }, 3000);
    }

    // 隐藏通知
    function hideNotification() {
        const notificationEl = document.getElementById('notification');
        notificationEl.classList.remove('translate-y-0', 'opacity-100');
        notificationEl.classList.add('translate-y-10', 'opacity-0');
    }

    // 创建用户名称显示元素
    function createUserNameLink(username) {
        // 移除已存在的用户元素
        if (userNameLink) {
            userNameLink.remove();
        }

        // 创建新的用户名称元素
        userNameLink = document.createElement('button');
        userNameLink.id = 'userNameLink';
        userNameLink.className = 'register-login-btn'; // 确保与原按钮样式一致
        userNameLink.textContent = `Hi, ${username}`;

        // 添加点击事件
        userNameLink.addEventListener('click', () => {
            const confirmLogout = confirm('确定要退出登录吗？');
            if (confirmLogout) {
                logoutHandler();
            }
        });

        // 插入到注册/登录按钮容器中
        const container = document.querySelector('.register-login');
        if (container) {
            // 移除原有的注册/登录按钮
            const originalButtons = container.querySelectorAll('button');
            originalButtons.forEach(btn => {
                if (btn.id !== 'userNameLink') {
                    btn.remove();
                }
            });

            // 插入新的用户名称按钮
            container.appendChild(userNameLink);
        }
    }

    // 退出登录处理函数
    function logoutHandler() {
        // 显示原始按钮
        const container = document.querySelector('.register-login');
        if (container) {
            // 移除用户名称按钮
            if (userNameLink) {
                userNameLink.remove();
                userNameLink = null;
            }

            // 创建并添加注册按钮
            const registerBtn = document.createElement('button');
            registerBtn.id = 'registerBtn';
            registerBtn.className = 'register-login-btn';
            registerBtn.textContent = '注册';
            registerBtn.onclick = openRegisterModal;

            // 创建分隔符
            const separator = document.createElement('span');
            separator.textContent = '丨';

            // 创建并添加登录按钮
            const loginBtn = document.createElement('button');
            loginBtn.id = 'loginBtn';
            loginBtn.className = 'register-login-btn';
            loginBtn.textContent = '登录';
            loginBtn.onclick = openLoginModal;

            // 添加到容器
            container.appendChild(registerBtn);
            container.appendChild(separator);
            container.appendChild(loginBtn);
        }

        // 清除用户会话
        localStorage.removeItem('currentUser');

        // 显示退出成功通知
        showNotification('成功', '已退出登录', 'success');
    }

    // 检查用户是否已登录
    function checkLoginStatus() {
        const userData = localStorage.getItem('currentUser');

        if (userData) {
            try {
                const user = JSON.parse(userData);
                // 显示用户名称
                createUserNameLink(user.username);

                // 调用自动登录回调
                if (typeof callbacks.onAutoLogin === 'function') {
                    callbacks.onAutoLogin(user);
                }

                return true;
            } catch (error) {
                console.error('解析用户数据失败:', error);
                return false;
            }
        }

        return false;
    }

    // 初始化事件监听器
    function initEventListeners() {
        // 关闭注册模态框
        document.getElementById('closeRegisterModal').addEventListener('click', () => {
            animateModal(registerModal, registerModalContent, false);
        });

        // 关闭登录模态框
        document.getElementById('closeLoginModal').addEventListener('click', () => {
            animateModal(loginModal, loginModalContent, false);
        });

        // 切换到登录
        document.getElementById('switchToLogin').addEventListener('click', () => {
            animateModal(registerModal, registerModalContent, false);
            setTimeout(() => {
                animateModal(loginModal, loginModalContent, true);
            }, 300);
        });

        // 切换到注册
        document.getElementById('switchToRegister').addEventListener('click', () => {
            animateModal(loginModal, loginModalContent, false);
            setTimeout(() => {
                animateModal(registerModal, registerModalContent, true);
            }, 300);
        });

        // 点击模态框外部关闭
        registerModal.addEventListener('click', (e) => {
            if (e.target === registerModal) {
                animateModal(registerModal, registerModalContent, false);
            }
        });

        loginModal.addEventListener('click', (e) => {
            if (e.target === loginModal) {
                animateModal(loginModal, loginModalContent, false);
            }
        });

        // 关闭通知
        document.getElementById('closeNotification').addEventListener('click', hideNotification);

        // 注册表单提交
        registerForm.addEventListener('submit', async (e) => {
            e.preventDefault();

            const username = document.getElementById('regUsername').value.trim();
            const email = document.getElementById('regEmail').value.trim();
            const password = document.getElementById('regPassword').value;

            // 简单验证
            if (!username || !email || !password) {
                showNotification('错误', '请填写所有必填字段', 'error');
                return;
            }

            // 邮箱格式验证
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                showNotification('错误', '请输入有效的邮箱地址', 'error');
                return;
            }

            // 密码长度验证
            if (password.length < 6) {
                showNotification('错误', '密码长度至少需要6个字符', 'error');
                return;
            }

            try {
                // 检查邮箱是否已注册
                const userByEmail = await getUserByEmail(email);
                if (userByEmail) {
                    showNotification('错误', '该邮箱已被注册', 'error');
                    return;
                }

                // 检查用户名是否已注册
                const userByUsername = await getUserByUsername(username);
                if (userByUsername) {
                    showNotification('错误', '该用户名已被使用', 'error');
                    return;
                }

                // 创建用户对象
                const newUser = {
                    username,
                    email,
                    password,
                    createdAt: new Date().toISOString()
                };

                // 添加用户到数据库
                await addUser(newUser);

                // 注册成功
                showNotification('成功', '注册成功，请登录', 'success');
                registerForm.reset();
                animateModal(registerModal, registerModalContent, false);
                setTimeout(() => {
                    animateModal(loginModal, loginModalContent, true);
                }, 300);

                // 调用注册成功回调
                if (typeof callbacks.onRegisterSuccess === 'function') {
                    callbacks.onRegisterSuccess(newUser);
                }
            } catch (error) {
                showNotification('错误', error, 'error');
                console.error('注册错误:', error);
            }
        });

        // 登录表单提交
        loginForm.addEventListener('submit', async (e) => {
            e.preventDefault();

            const identifier = document.getElementById('loginIdentifier').value.trim();
            const password = document.getElementById('loginPassword').value;
            const rememberMe = document.getElementById('rememberMe').checked;

            // 简单验证
            if (!identifier || !password) {
                showNotification('错误', '请填写所有必填字段', 'error');
                return;
            }

            try {
                let user;

                // 判断是邮箱还是用户名
                if (identifier.includes('@')) {
                    // 通过邮箱查找
                    user = await getUserByEmail(identifier);
                } else {
                    // 通过用户名查找
                    user = await getUserByUsername(identifier);
                }

                if (!user) {
                    showNotification('错误', '用户不存在', 'error');
                    return;
                }

                if (user.password !== password) {
                    showNotification('错误', '密码不正确', 'error');
                    return;
                }

                // 登录成功
                showNotification('成功', `欢迎回来，${user.username}！`, 'success');
                loginForm.reset();
                animateModal(loginModal, loginModalContent, false);

                // 存储用户会话
                if (rememberMe) {
                    localStorage.setItem('currentUser', JSON.stringify({
                        username: user.username,
                        email: user.email
                    }));
                }

                // 调用登录成功回调
                if (typeof callbacks.onLoginSuccess === 'function') {
                    callbacks.onLoginSuccess(user);
                }

                // 创建用户名称显示
                createUserNameLink(user.username);
            } catch (error) {
                showNotification('错误', '登录失败，请稍后再试', 'error');
                console.error('登录错误:', error);
            }
        });
    }

    // 初始化认证弹窗
    window.initAuthModal = async function (options = {}) {
        // 存储回调函数
        callbacks = {
            onRegisterSuccess: options.onRegisterSuccess,
            onLoginSuccess: (user) => {
                // 先执行用户传入的回调
                if (typeof options.onLoginSuccess === 'function') {
                    options.onLoginSuccess(user);
                }
                // 再执行内部用户显示逻辑
                createUserNameLink(user.username);
            },
            onAutoLogin: options.onAutoLogin // 新增：自动登录回调
        };

        try {
            // 创建弹窗元素
            createModalElements();

            // 初始化数据库
            await openDatabase();
            console.log('数据库已成功初始化');

            // 初始化事件监听器
            initEventListeners();

            // 检查登录状态
            const isLoggedIn = checkLoginStatus();
            console.log('用户登录状态:', isLoggedIn ? '已登录' : '未登录');
        } catch (error) {
            console.error('初始化认证弹窗失败:', error);
            // 可以在这里显示一个全局错误通知
        }
    };

    // 打开注册弹窗
    window.openRegisterModal = function () {
        animateModal(registerModal, registerModalContent, true);
    };

    // 打开登录弹窗
    window.openLoginModal = function () {
        animateModal(loginModal, loginModalContent, true);
    };
})();

// 登录注册弹窗
document.addEventListener('DOMContentLoaded', () => {
    // 确保按钮存在
    const registerBtn = document.getElementById('registerBtn');
    const loginBtn = document.getElementById('loginBtn');

    if (!registerBtn || !loginBtn) {
        console.error('未找到登录/注册按钮');
        return;
    }

    // 初始化认证弹窗
    initAuthModal({
        onRegisterSuccess: (user) => {
            console.log('用户注册成功:', user);
        },
        onLoginSuccess: (user) => {
            console.log('用户登录成功:', user);
        },
        onAutoLogin: (user) => {
            console.log('用户自动登录:', user);
            // 这里可以添加页面特定的自动登录处理逻辑
        }
    });

    // 绑定点击事件 - 使用更可靠的方式
    registerBtn.onclick = openRegisterModal;
    loginBtn.onclick = openLoginModal;

    console.log('认证弹窗初始化完成，按钮事件已绑定');
});